//
//  SJHomeTableViewController.swift
//  SJWeiboSwift
//
//  Created by app;e on 15/9/29.
//  Copyright © 2015年 world. All rights reserved.
//  首页

import UIKit
import SVProgressHUD

class SJHomeTableViewController: SJBaseTableViewController,SJStatusCellDelegate {
    
    /// 缓存行高statusID:行高
    var rowHeighCache = [Int:CGFloat]()
    
 /// 当前选中的cell
    var selectedCell: SJStatusCell?
    
    ///绑定表格数据
    var statusList: [SJStatus]?{
        didSet{
            //刷新表格
            tableView.reloadData()
            
            refreshControl?.endRefreshing()
        }
    }
    /**
    收到内存警告,释放缓存,字典可以使用removeAll. 但是如果是使用NSCache缓存的时候就不能removeAll
    */
    override func didReceiveMemoryWarning() {
        rowHeighCache.removeAll()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //登陆后,userLoginView就为nil,给nil发送消息什么也不会发送
        userLoginView?.setupViewContent("visitordiscover_feed_image_smallicon", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        if !userLogin{//没有登陆
            return
        }
        //设置导航栏按钮
        setupNavBarButton()
        
        //准备tableView
        prepareTableView()
        
        prepareRefreshControl()
        
        }
    private func prepareRefreshControl(){
        
        refreshControl = SJRefreshControl()
        //给刷新控件添加刷新方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        //beginRefreshing 显示刷新控件, 但是不会触发刷新方法, 需要手动调用loadData方法
        refreshControl?.beginRefreshing()
        
        loadData()

    }
    
    //准备tableView
    private func prepareTableView(){
        //注册cell
        //转发cell
        tableView.registerClass(SJStatusForwardCell.self, forCellReuseIdentifier: SJStatusForwardCellReuseIdentifier)
        //原创cell
        tableView.registerClass(SJStatusNormCell.self, forCellReuseIdentifier: SJStatusNormalCellReuseIdentifier)
        //使用了缓存行高,就不能设置预估行高
        //        tableView.estimatedRowHeight = 200
        
        //设置分割线样式
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None

    }
    ///判断是否是上拉刷新
    var pullRefreshFlag = false
    
    ///加载微博数据
    func loadData(){
        //下拉刷新的微博的id
        var since_id = self.statusList?.first?.id ?? 0 //第一次没有值返回0
        var max_id = 0
        //判断是否是上拉刷新
        if pullRefreshFlag {//如果是上拉刷新
            since_id = 0 // since_id 与 max_id 不能同时为0, 或者同时有值
            max_id = self.statusList?.last!.id ?? 0
        }
        
        SJStatus.loadStauts(max_id, since_id: since_id) { (statuses, error) -> () in
            if error != nil {
                //有错误
                SVProgressHUD.showInfoWithStatus("您的网络不给你")
            }
            if statuses == nil {
                //网络请求没有错误,但是返回数据为空
                print("没有数据")
            }
            //
            print("刷新了\(statuses!.count)条")
            
            if since_id > 0 {
                self.statusList = statuses! + self.statusList!
            }else if max_id > 0 {
                self.statusList = self.statusList! + statuses!
            } else{
                self.statusList = statuses
            }

        }
}

    
    
    ///设置导航栏按钮
    private func setupNavBarButton(){
        //判断是否登陆
        if  sharedUserAccount == nil {
            return
        }
 
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", hlightedImageName: nil)
        //右边button
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", hlightedImageName: nil)
        
        //添加顶部标题
        let titleButton = SJHomeTitleButton.titleButton((sharedUserAccount?.name)!)
        titleButton.addTarget(self, action: "titleBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
        
        let btn = navigationItem.rightBarButtonItem?.customView as! UIButton
        btn.addTarget(self, action: "showQRCode", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
    ///显示二维码
    func showQRCode(){
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        presentViewController(vc!, animated: true, completion: nil)
    }
    
    ///创建动画代理对象
    let popoVerAnimator = SJPopoverAnimator()
    
    /// titleBtn点击事件
     func titleBtnClick(){
    
        let sb = UIStoryboard(name: "SJFrendsGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("SJFrendsGroup")
        //自定义model
        //0.设置popover的frame
        popoVerAnimator.presentedFrame = CGRectMake(100, 56, 200, 240)
        //1.设置 转场 代理
        vc.transitioningDelegate = popoVerAnimator
        //2.设置model的样式为custom
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
    }
    
    //viewDidLoad只会调用一次, viewDidAppear会掉多次
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        userLoginView?.startAnimating()
    }
    
    
    // MARK: - tableView的数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return statusList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statusList![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(SJStatusCell.cellReuseIdentifier(status), forIndexPath: indexPath) as! SJStatusCell
        
        //设置代理
        cell.photoDelegate = self
        cell.status = statusList![indexPath.row]
        
        //判断是否是最后一行cell
        if indexPath.row == (statusList!.count - 1) {
            //最后一行, 开始让上拉刷新标志变为true
            pullRefreshFlag = true
            //加载数据
            loadData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //0.获取status模型
        let status = statusList![indexPath.row]

        //1.先看缓存中是否有行高
        if rowHeighCache[status.id] != nil {
            return rowHeighCache[status.id]!
        }
        
        //2.缓存中没有
        //2.1获取cell ,  用dequeue去缓冲池中取一个cel ,说明这个cell已经被用过, 这个cell的属性已经被赋值过.  如果需要准确的计算cell的行高, 需要重新根据cell的类名实例化一个新的cell
//        let cell = tableView.dequeueReusableCellWithIdentifier(SJStatusCell.cellReuseIdentifier(status)) as! SJStatusCell
        //获取重用表示的ID
        let  ID = SJStatusCell.cellReuseIdentifier(status)
        //创建一个类对象,默认是原创微博类型的
        var cellClass:AnyClass = SJStatusNormCell.self
        //判断重用表示类型
        if ID == SJStatusForwardCellReuseIdentifier {
            cellClass = SJStatusForwardCell.self
        }
        //根据cellClass创建cell对象
        //TODO:
       let cell = (cellClass as! SJStatusCell.Type).init()
        
        //2.2 存储到缓存字典中
        rowHeighCache[status.id] = cell.rowHeight(status)
        return cell.rowHeight(status)
    }
    
    // MARK: - statusCell的代理方法
    func statusCellDidSelectedPhoto(cell: SJStatusCell, index: Int) {
//        print(cell.status!.largePicURLs![index])
        //没有配图 直接返回
        if cell.status?.largePicURLs == nil{
            return
        }
        
        //保存选中的cell
        selectedCell = cell
        
        //图片浏览控制器
        let vc = SJPhotoBrowserController(imageURLs: cell.status!.largePicURLs!, photoIndex: index)
        
        //0.准备转场动画的素材
        presentImageView.sd_setImageWithURL(cell.status!.largePicURLs![index])
        presentImageView.contentMode = UIViewContentMode.ScaleAspectFill
        //让临时图片 与cell上图片重叠
        presentImageView.frame = cell.screenFrameOfPhotoIndex(index)
        
        presentFrame = cell.fullScreenFrameOfPhotoIndex(index)
        //自定义modal 动画
        //1.设置代理
        vc.transitioningDelegate = self
        //2.设置动画类型
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        //从首页控制器 modal 到图片浏览控制器
        presentViewController(vc, animated: true, completion: nil)
    }
    
    
    //临时的图片视图
    private lazy var presentImageView = UIImageView()
    //临时图片的位置
    private var presentFrame = CGRectZero
    
    //modal or dismiss 状态的表示
    var isPresented = false
}

extension SJHomeTableViewController : UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{
    // MARK: UIViewControllerTransitioningDelegate 
    //返回一个提供 modal动画的 对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    //返回一个提供 disMiss动画的 对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    
    
    
    // MARK: UIViewControllerAnimatedTransitioning 代理
    //动画时间
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    // 动画内容
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let keyForView = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let tragetView = transitionContext.viewForKey(keyForView)
        //0.判断view是否有值
        if tragetView == nil{
            return
        }
        //1.添加view
        transitionContext.containerView()?.addSubview(tragetView!)
        //2.动画
        if isPresented{
            tragetView?.alpha = 0
            //2.添加临时的imageView
            transitionContext.containerView()?.addSubview(presentImageView)

            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                //让临时图片 放大到 相对于全屏的位置
                self.presentImageView.frame = self.presentFrame
                
                }, completion: { (_) -> Void in
                    //显示真实的图片
                    tragetView?.alpha = 1

                    //移除临时图片
                    self.presentImageView.removeFromSuperview()
                    
                    //动画完成
                    transitionContext.completeTransition(true)
            })
        }else {
            //0.获取要缩放的图片
            let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! SJPhotoBrowserController
            let imageView = fromVC.getImageView()
            //设置填充模式
            imageView.contentMode = UIViewContentMode.ScaleAspectFill
            
            //1.恢复的位置
            let targetFrame = selectedCell?.screenFrameOfPhotoIndex(fromVC.getCurrentImageIndex())
            
            //2.将imageView添加到容器视图中
            transitionContext.containerView()?.addSubview(imageView)
            //叠加形变(scrollView本事也会发生缩放)
            imageView.transform = CGAffineTransformScale(imageView.transform, tragetView!.transform.a, tragetView!.transform.a)
            //设置imageView的中心位置(不设置位置,默认添加到(0,0)点,最后会从原点开始动画)
            imageView.center = tragetView!.center
            
            //3.删除tragetView
             tragetView?.removeFromSuperview()
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
//                tragetView?.alpha = 0
                //设置恢复位置
                imageView.frame = targetFrame!
                }, completion: { (_ ) -> Void in
                   imageView.removeFromSuperview()
                    //动画完成
                    transitionContext.completeTransition(true)
            })
        }
        
    }
    
}
